const Upyun = require('../../utils/upyun-wxapp-sdk')
const upyun = new Upyun({
  bucket: 'feijiu-img5',
  operator: 'feijiu',
  getSignatureUrl: 'https://zsbpt.zaisubao.cn/index.php/Api/Feijiu/getSignature'
  // getSignatureUrl: 'https://v0.api.upyun.com'
})
let date = new Date;
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();  
const hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
const minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
const second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
const milliSeconds = date.getMilliseconds();
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    gqlist:[],
    FjLoginLog:wx.getStorageSync('FjLoginLog'),  
    gqshid:1,
    navindex:1,
    spintCurrPage:1,
    IsAddBtn:0,
    VideoAuth:0,
    VideoMess:'',
    splist:[],
    spshid:1,
    allsplist:[],
    tgnum:0,
    wtgnum:0,
    shnum:0,    
    xcplist:[],
    is_play:false,
    vodurl:'',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (app.checkFjLogin()) {
      this.setData({
        FjLoginLog: wx.getStorageSync('FjLoginLog')
      })
      this.getGqList()
      // this.getXspList()
    } else {
      wx.redirectTo({ url: '../../pages/login/index' }); 
    }
  },
  //菜单上总切换
  changeNav:function (e) {
    if (e.currentTarget.dataset.navindex != this.data.navindex) {
      this.setData({
        navindex:e.currentTarget.dataset.navindex
      })
      if (this.data.navindex == 1) {
        this.getGqList()
      }   
      if (this.data.navindex == 2) {
        this.getXspList()
      } 
      if (this.data.navindex == 3) {
        this.getXcpList()
      }      
    }    
  },
  changespMenu:function (e) {
    if (e.currentTarget.dataset.spshid != this.data.spshid) {
      this.setData({
        spshid:e.currentTarget.dataset.spshid
      }) 
      // var arr = this.data. 
      this.getXspList();
    }

  },
  getXcpList:function () {
    var that = this;
    var api_input = {
      LoginUID:this.data.FjLoginLog.UID,
      Type:2,
      shid:-1,
      intCurrPage:this.data.spintCurrPage
    } 
    app.getDaoPost('api/FeijiuApp/Feijiu_Get_UserVideoList',api_input,function (r) {
      console.log(r)
      if (r.code == 200) {
        that.setData({
          IsAddBtn:r.data.IsAddBtn,
          VideoAuth:r.data.VideoAuth,
          VideoMess:r.data.VideoMess,          
        })
        if (r.data.VideoAuth == 1) {
          var xcplist = r.data.data.ds;
          var thisarr = [];
          for (var i = 0; i < xcplist.length; i++) {
            xcplist[i].VideoDuration = that.formatTime(xcplist[i].VideoDuration);
          }
          that.setData({
            xcplist:xcplist,            
          })
        }
      }
    })       
  },
  /**
   * 获取所有视频列表
   * @return {[type]} [description]
   */
  getXspList:function () {    
    var that = this;
    //LoginUID：登录用户ID，Type：1小视频 2宣传片，shid：-1全部 0未审核 1审核通过  2未通过 ，intCurrPage：当前页数     
    var api_input = {
      LoginUID:this.data.FjLoginLog.UID,
      Type:1,
      shid:-1,
      intCurrPage:this.data.spintCurrPage
    }
    app.getDaoPost('api/FeijiuApp/Feijiu_Get_UserVideoList',api_input,function (r) {
      console.log(r)
      if (r.code == 200) {
        that.setData({
          IsAddBtn:r.data.IsAddBtn,
          VideoAuth:r.data.VideoAuth,
          VideoMess:r.data.VideoMess,          
        })
        if (r.data.VideoAuth == 1) {
          var splist = r.data.data.ds;
          var thisarr = [];
          for (var i = 0; i < splist.length; i++) {
            splist[i].VideoDuration = that.formatTime(splist[i].VideoDuration);
            if (splist[i].shid == that.data.spshid) {
              thisarr.push(splist[i]);
            }
          }
          that.setData({
            splist:thisarr,
            allsplist:splist,
            tgnum:that.getArrNum(splist,1),
            wtgnum:that.getArrNum(splist,2),
            shnum:that.getArrNum(splist,0)
          })
        }
      }
    })
  },
  /**
   * 获取指定条件的数组个数
   * @param  {[type]} arr    [description]
   * @param  {[type]} status [description]
   * @return {[type]}        [description]
   */
  getArrNum:function (arr,status) {
    var thisarr = [];
    for (var i = 0; i < arr.length; i++) {
      if (arr[i].shid == status) {
        thisarr.push(arr[i]);
      }
    }    
    return thisarr.length;
  },
  //我发布的供求列表
  getGqList:function () {
   var that = this;
   var url = "api/FeijiuApp/GetMyFabuByUIDAll?uid="+this.data.FjLoginLog.UID+"&shid="+this.data.gqshid+"&intCurrPage=0&strRSA=";
   app.getDaoGet(url,function (r) {    
    console.log(r)
      if (r.code == 200) {        
        for (var i = 0; i < r.data.data.ds.length; i++) {
          if (r.data.data.ds[i].photo) {
            r.data.data.ds[i].photo1 = r.data.data.ds[i].photo.split("|");
          }else{
            r.data.data.ds[i].photo1 = '';
          }
          if (r.data.data.ds[i].yy === null) {
            r.data.data.ds[i].yy = '正在审核中'
          }
        }
        that.setData({
          gqlist:r.data.data.ds
        })
      }
   })
  },
  //供求去详细页
  toInfo:function (e) {
    if (this.data.gqshid == 1) {
      wx.navigateTo({
        url: '../gongqiuxinxi/detailed?gqid='+e.currentTarget.dataset.gqid
      })
    }
  }, 
  //供求信息是否审核切换
  qgchange:function (e) {
    if (e.currentTarget.dataset.shid != this.data.gqshid) {
      this.setData({
        gqshid:e.currentTarget.dataset.shid
      })
      this.getGqList();
    }
  },  

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
      if (this.data.navindex == 1) {
        this.getGqList()
      }   
      if (this.data.navindex == 2) {
        this.getXspList()
      } 
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  formatTime:function (seconds){
      let hour = Math.floor(seconds / 3600) >= 10 ? Math.floor(seconds / 3600) : '0' + Math.floor(seconds / 3600);
      seconds -= 3600 * hour;
      let min = Math.floor(seconds / 60) >= 10 ? Math.floor(seconds / 60) : '0' + Math.floor(seconds / 60);
      seconds -= 60 * min;
      let sec = seconds >= 10 ? seconds : '0' + seconds;
      return min + ':' + sec;
  },

  tofabu:function () {
    if (this.data.IsAddBtn == 1) {
    var that = this;
    wx.chooseVideo({
      sourceType: ['album','camera'],
      maxDuration: 60,
      camera: 'back',
      success(r) {
        if (r.size > 10000000) {
           app.tishi('您上传的视频已超过10M!请缩小后再上传!');return false;
        }
        // console.log(r);return false;
        var index= r.tempFilePath.lastIndexOf("\.");
        var kuozhan = r.tempFilePath.substring(index+1,r.tempFilePath.length);
        var name = that.Appendzero(day)+''+hour+''+minute+''+second+''+milliSeconds+''+that.threeRand()+'.'+kuozhan;
        var vodSrc = r.tempFilePath;
        wx.showLoading({
          title: "视频正在上传中"       
        })  
        upyun.upload({
          localPath: vodSrc,
          remotePath: '/video/shop/'+year+'/'+that.Appendzero(month)+'/'+that.Appendzero(day)+'/'+name,
          success: function (res) {
            wx.showToast({
              title: '上传成功',
              icon: 'success',
              duration: 1000
            })            
            if (res.statusCode == 200) {
              res.data = JSON.parse(res.data);
              if (res.data.code == 200) {
                setTimeout(function () {
                  wx.navigateTo({
                    url: '../shipin/edit?url='+res.data.url+'&duration='+Math.round(r.duration)+'&type=1&navindex=3'
                  })
                },1000)
              }else{
                app.tishi('视频上传失败,请重试!')
              }
              
            }else{
              app.tishi('视频上传失败,请重试!')
            }

          },
          fail: function ({errMsg}) {
            console.log('uploadImage fail, errMsg is', errMsg)
          },
         
        })        
      }
    })
    }else{
      app.tishi(this.data.VideoMess)
    }
  },

  tofabuxcp:function () {
    if (this.data.IsAddBtn == 1) {
    var that = this;
    wx.chooseVideo({
      sourceType: ['album','camera'],
      maxDuration: 60,
      camera: 'back',
      success(r) {
        if (r.size > 10000000) {
           app.tishi('您上传的视频已超过10M!请缩小后再上传!');return false;
        }
        // console.log(r);return false;
        var index= r.tempFilePath.lastIndexOf("\.");
        var kuozhan = r.tempFilePath.substring(index+1,r.tempFilePath.length);
        var name = that.Appendzero(day)+''+hour+''+minute+''+second+''+milliSeconds+''+that.threeRand()+'.'+kuozhan;
        var vodSrc = r.tempFilePath;
        wx.showLoading({
          title: "视频正在上传中"       
        })  
        upyun.upload({
          localPath: vodSrc,
          remotePath: '/video/shop/'+year+'/'+that.Appendzero(month)+'/'+that.Appendzero(day)+'/'+name,
          success: function (res) {
            wx.showToast({
              title: '上传成功',
              icon: 'success',
              duration: 1000
            })            
            if (res.statusCode == 200) {
              res.data = JSON.parse(res.data);
              if (res.data.code == 200) {
                setTimeout(function () {
                  wx.navigateTo({
                    url: '../shipin/edit?url='+res.data.url+'&duration='+Math.round(r.duration)+'&type=2&navindex=3'
                  })
                },1000)
              }else{
                app.tishi('视频上传失败,请重试!')
              }
              
            }else{
              app.tishi('视频上传失败,请重试!')
            }

          },
          fail: function ({errMsg}) {
            console.log('uploadImage fail, errMsg is', errMsg)
          },
         
        })        
      }
    })
    }else{
      app.tishi(this.data.VideoMess)
    }
  },

  tophone:function (e) {
    wx.makePhoneCall({
      phoneNumber: '4008116831'            
    })
  },
  Appendzero:function(obj){
      if(obj<10) return "0" +""+ obj;
      else return obj;
  },
  threeRand:function () {
    var rand = "";
    for(var i = 0; i < 3; i++){
        var r = Math.floor(Math.random() * 10);
        rand += r;
    }
    return rand;
  },
  delete:function (e) {
    var id = e.currentTarget.dataset.id;
    var idx = e.currentTarget.dataset.idx;
    var that = this;
    wx.showModal({
     // title: '提示',
     content: '确认要删除视频吗?删除后不可恢复',
     success: function (res) {
       if (res.confirm) {
          var api_input = {
            ID:id
          }
         app.getDaoPost('api/FeijiuApp/Feijiu_Del_UserVideo',api_input,function (r) {
            console.log(r)
            if (r.code == 200) {
              app.tishi('删除成功!');
              that.getXspList();
            }else{
              app.tishi('删除失败!')
            }
         })
       } else {
       }
     }
    })    

    // 
  },
  videoPlay:function (e) {
    console.log(e)
    var idx = e.currentTarget.dataset.idx;
    var api_input = {
      ID:this.data.splist[idx].id
    }
    var that = this;
    // app.getDaoPost('api/FeijiuApp/Feijiu_Add_UserVideoViews',api_input,function (r) {

    // })    
    this.setData({
      is_play:true,
      vodurl:this.data.splist[idx].Video
    })
    this.videoContext = wx.createVideoContext('myVideo');
  },
  guanbi_sp:function () {
    this.setData({
      is_play:false,
    })
  }  


})